const gulp = require('gulp')
const cssmin = require('gulp-cssmin')
const sass = require('gulp-sass')(require('sass'))
const autoprefixer = require('gulp-autoprefixer')
const htmlmin = require('gulp-htmlmin')
const fileinclude = require('gulp-file-include')
const uglify = require('gulp-uglify')
const babel = require('gulp-babel')
const del = require('del')
const webserver = require('gulp-webserver')
function cssHandler(){
    return gulp
        .src('./src/css/*.css')
        .pipe(autoprefixer())
        .pipe(cssmin())
        .pipe(gulp.dest('./dist/css/'))
}
function sassHandler(){
    return gulp
        .src('./src/sass/*.scss')
        .pipe(sass())
        .pipe(autoprefixer())
        .pipe(cssmin())
        .pipe(gulp.dest('./dist/sass/'))
}
function htmlHandler(){
    return gulp
        .src('./src/views/*.html')
        .pipe(fileinclude({
            basepath:'./src/components/',
            prefix:'@-@'
        }))
        .pipe(htmlmin({
            collapseWhitespace:true,
            removeAttributeQuotes:true,
            removeEmptyAttributes:true,
            removeComments:true,
            removeScriptTypeAttributes:true,
            removeStyleLinkTypeAttributes:true,
            collapseBooleanAttributes:true,
            minifyJS:true,
            minifyCSS:true
        }))
        .pipe(gulp.dest('./dist/views/'))
}
function jsHandler(){
    return gulp
        .src('./src/js/*.js')
        .pipe(babel({ presets:['@babel/preset-env']}))
        .pipe(uglify())
        .pipe(gulp.dest('./dist/js/'))
}
function imgHandler(){
    return gulp
        .src('./src/images/**.*')
        .pipe(gulp.dest('./dist/images/'))
}
function delHandler(){
    return del(['./dist/'])
}
function serverHandler(){
    return gulp
        .src('./dist/')
        .pipe(webserver({
            host:'localhost',
            port:8081,
            open:'./views/index.html',
            livereload:true
        }))
}
function fontHandler(){
    return gulp
        .src('./src/fonts/**.*')
        .pipe(gulp.dest('./dist/fonts'))
}

function watchHandler(){
    gulp.watch('./src/css/*.css',cssHandler)
    gulp.watch('./src/sass/*.scss',sassHandler)
    gulp.watch('./src/fonts/**.*',fontHandler)
    gulp.watch('./src/views/*.html',htmlHandler)
    gulp.watch('./src/components/*.html',htmlHandler)
    gulp.watch('./src/js/*.js',jsHandler)
    gulp.watch('./src/images/**.*',imgHandler)
}

const _default = gulp.series(
    delHandler,
    gulp.parallel(cssHandler,sassHandler,htmlHandler,fontHandler,jsHandler,imgHandler),
    serverHandler,
    watchHandler
)
module.exports = {
    cssHandler,
    sassHandler,
    htmlHandler,
    jsHandler,
    fontHandler,
    imgHandler,
    serverHandler,
    default:_default
}